/*
题目描述：输出链表中倒数第 k 个结点值
方法：
定义快慢指针，注意代码的健壮性
 */
public class E22 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = new ListNode(6);

        int k = 3;
        ListNode res = FindKthToTail(head, k);
        System.out.println(res.value);
    }

    public static ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k == 0){
            return null;
        }
        ListNode pAhead = head;
        ListNode pBehind = head;
        for(int i = 0; i < k; i++){
            if(pAhead != null){
                pAhead = pAhead.next;
            }
            else{
                return null;
            }
        }
        while(pAhead != null){
            pAhead = pAhead.next;
            pBehind = pBehind.next;
        }
        return pBehind;
    }

}
